import React from 'react';
import PropTypes from 'prop-types';
import { Form, Input, Select, Modal, Icon, message } from 'antd';
import IconSelect from './iconSelect';
import { uniqueArray } from '../../utils/util';

const FormItem = Form.Item;

const formItemLayout = {
	labelCol: {
		span: 6,
	},
	wrapperCol: {
		span: 14,
	},
};
const styles = {
	item: {
		position: 'relative',
	},
	icon: {
		position: 'absolute',
		right: '0',
		top: '5px',
		border: '1px solid #ccc',
		borderRadius: '100px',
		padding: '4px',
		cursor: 'pointer'
	},
	btn: {
		position: 'absolute',
		right: '0px',
		top: '5px',
		zIndex: '1000',
	},
	input: {
		width: '40%',
		marginRight: '20px'
	}
};

const types = {
	1: '导航菜单',
	2: '功能模块',
};

class MyModal extends React.Component {
	state = {
		versions: [{}]
	}

	componentDidUpdate(prevProps) {
		const { form, data, versionList } = this.props;
		const { setFieldsValue } = form;
		if (prevProps.versionList !== versionList) {
			this.setState({ versions: versionList && versionList.length && versionList || [{}] });
		}
		if (!data || prevProps.data === data) return;
		setFieldsValue(data);
		this.type = data.permissionType;
	}

	onOk = () => {
		const { form: { validateFields }, onOk, data } = this.props;
		validateFields((err, d) => {
			if (!err) {
				if (data.id) {
					d.id = data.id;
				} else {
					d = { ...data, ...d };
				}
				d.permissionKey = d.permissionKey || d.uri;

				const { versions } = this.state;
				const hasEmpty = versions.some(v => !v.versionName || !v.versionCode);
				if (!hasEmpty) d.versions = versions;
				onOk(d);
			}
		});
	}

	add = () => {
		const { versions } = this.state;
		const hasEmpty = versions.some(v => !v.versionName || !v.versionCode);
		console.log('versions', versions, hasEmpty);
		if (hasEmpty) {
			message.warning('请输入版本信息');
			return;
		}
		versions.push({});
		this.setState({ versions });
	}

	del = (idx) => {
		const { versions } = this.state;
		const arr = versions.filter((v, i) => i !== idx);
		this.setState({ versions: arr });
	}

	versionChange = (k, v, i) => {
		const { versions } = this.state;
		const arr = versions.concat();
		arr[i] = { ...versions[i], [k]: v.target.value, sort: i + 1 };
		this.setState({ versions: arr });
	}

	iconSelect = (v) => {
		if (!v) return;
		const { form: { setFieldsValue } } = this.props;
		setFieldsValue({ icon: v });
		this.setState({ iconModal: false });
	}

	render() {
		const { form, data, isAdmin } = this.props;
		const { getFieldDecorator } = form;
		const item = data || {};
		const { versions } = this.state;
		// console.log('item.permissionName', item.permissionName, versions);
		return (
			<Modal
				title={item.id ? `编辑${item.permissionName}` : '新增权限'}
				visible={!!data}
				onOk={this.onOk}
				onCancel={this.props.handleCancel}
			>
				<Form layout="horizontal">
					<FormItem label="名称" hasFeedback {...formItemLayout}>
						{getFieldDecorator('permissionName', {
							initialValue: item.permissionName,
							rules: [
								{ required: true, message: '请输入权限名称!' },
								{ pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]{1,20}$/, message: '需要1-20个字符，只能输入中文、数字或英文字母' }
							]
						})(<Input />)}
					</FormItem>
					<FormItem label="类型" hasFeedback {...formItemLayout}>
						{getFieldDecorator('permissionType', {
							initialValue: item.permissionType
						})(<Select defaultValue="1" style={{ width: 120 }} onChange={v => this.type = v}>
							{Object.keys(types).map(k => <Option value={parseInt(k, 10)}>{types[k]}</Option>)}
						</Select>)}
					</FormItem>
					<FormItem label="后端接口" hasFeedback {...formItemLayout}>
						{getFieldDecorator('uri', {
							initialValue: item.uri,
							rules: [
								{ required: true, message: '请输入uri!' },
								{ pattern: /^[^\s]{1,100}$/, message: '最多能输入100个字符，并不允许输入空格' }
							]
						})(<Input />)}
					</FormItem>
					{this.type === 1
						? <FormItem label="页面URL" hasFeedback {...formItemLayout}>
							{getFieldDecorator('permissionKey', {
								initialValue: item.permissionKey,
								rules: [
									{ required: true, message: '请输入路径!' },
									{ pattern: /^[^\s]{1,50}$/, message: '最多能输入50个字符，并不允许输入空格' }
								]
							})(<Input />)}
						</FormItem>
						: null
					}
					<FormItem label="ICON" hasFeedback {...formItemLayout}>
						{getFieldDecorator('icon', {
							initialValue: item.icon,
							rules: [
								{ required: true, message: '请输入图标!' },
								{ max: 50, message: '最多能输入50个字符' }
							]
						})(<Input onClick={() => this.setState({ iconModal: true })} />)}
						<IconSelect show={this.state.iconModal} onCancel={() => this.setState({ iconModal: false })} onOk={this.iconSelect} />
					</FormItem>
					{isAdmin ? (
						<FormItem label="可用版本" {...formItemLayout}>
							{
								(item.permissionName ? uniqueArray(versions, 'id') : versions).map((v, i) => {
									// versions.map((v, i) => {
									return (
										<div style={styles.item}>
											<Input placeholder="请输入版本名称" onChange={(v) => this.versionChange('versionName', v, i)} style={styles.input} value={v.versionName} />
											<Input placeholder="请输入版本标识码" onChange={(v) => this.versionChange('versionCode', v, i)} style={styles.input} value={v.versionCode} />
											{i !== 0 ? <Icon type="minus" style={styles.icon} onClick={() => this.del(i)} /> : null}
											{i === 0 ? <Icon type="plus" style={styles.icon} onClick={() => this.add(i)} /> : null}
										</div>
									);
								})
							}
						</FormItem>
					) : null}
				</Form>
			</Modal>
		);
	}
}

MyModal.propTypes = {
	data: PropTypes.object,
	onOk: PropTypes.func,
};

export default Form.create()(MyModal);
